package ifconnect.model.connection;

import java.io.Serializable;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class ConnectionManager implements ConnectionManagerIF, Serializable {

    private EntityManagerFactory entityManagerFactory;
    private EntityManager entityManager;

    private static ConnectionManagerIF instance = null;

    private ConnectionManager() {
        conectarFabrica();
        conectarGerenciador();
    }

    public static ConnectionManagerIF getInstance(){
        if(instance == null){
            instance = new ConnectionManager();
        }
        return instance;
    }
    
    public void conectarFabrica() {
        if(entityManagerFactory==null){
            this.entityManagerFactory = Persistence.createEntityManagerFactory("IFConnectPU");
        }else{
            System.out.println("EntityManagerFactory ABERTO!");
        }
    }

    public void conectarGerenciador() {
        if(entityManager==null){
            this.entityManager = entityManagerFactory.createEntityManager();
        }else{
            System.out.println("EntityManager ABERTO!");
        }
    }

    public void liberarFabrica() {
        if (entityManagerFactory != null) {
            entityManagerFactory.close();
            System.out.println("EntityManagerFactory FECHADO!");
        }
    }

    public void liberarGerenciador() {
        if (entityManager != null) {
            entityManager.close();
            System.out.println("EntityManager FECHADO!");
        }
    }

    public EntityManager getEntityManager() {
        return entityManager;
    }

}
